
<template>
  <div>
    <input type="file" @change="onFileChange" accept="image/*" capture="camera">

    <img style="width: 200px;height: 150px;" v-if="photoBase64" :src="photoBase64" alt="">
    <button @click="submitPhoto">上传</button>
  </div>
</template>

<script>
export default {
  data(){
    return{
      photoBase64: ""
    }
  },
  methods: {
    onFileChange(e) {
      console.log(e)
      const file = e.target.files[0];
      this.convertToBase64(file).then(base64 => {
        console.log(base64)
        this.photoBase64 = base64;
      });
    },
    convertToBase64(file) {
      return new Promise((resolve, reject) => {
        this.photoBase64 = ""
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
        reader.readAsDataURL(file);
      });
    },
    submitPhoto() {
      if (!this.photoBase64) {
        alert('请先拍照。');
        return;
      }
      const formData = new FormData();
      formData.append('photo', this.photoBase64);

      // 使用Axios或者其他HTTP库发送formData到服务器
      // axios.post('your-upload-url', formData, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   }
      // }).then(response => {
      //   console.log(response.data);
      // }).catch(error => {
      //   console.error(error);
      // });
    }
  },
};
</script>

<style>
</style>